public class Test37 {
    public static  ListNode findFirstCommonNode(ListNode head1,ListNode head2){
        int length1 = getLength(head1);
        int length2 = getLength(head2);

        int diff = length1 - length2;
        ListNode longNode = head1;
        ListNode shortNode = head2;

        if (diff < 0){
            longNode = head2;
            shortNode = head1;
            diff = -diff;
        }

        for (int i =0;i<diff;i++){
            longNode = longNode.next;
        }
        while (longNode != null && shortNode != null && longNode != shortNode){
            longNode = longNode.next;
            shortNode = shortNode.next;
        }
        return longNode;

    }
    public static int getLength(ListNode head){
        ListNode temp = head;
        int res =0;
        while(temp != null){
            temp = temp.next;
            res ++;
        }
        return res;
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(6);
        ListNode n7 = new ListNode(7);

        n1.next = n2;
        n2.next = n3;
        n3.next = n6;
        n6.next = n7;

        n4.next = n5;
        n5.next = n6;

        System.out.println(findFirstCommonNode(n1, n4).val);
    }
}
